package com.zlb.leyaoxiu2.sqlite;

import com.zlb.leyaoxiu2.live.common.utils.UUIDUtil;
import com.zlb.leyaoxiu2.live.protocol.tcp.PrivateChatNotify;
import com.zlb.leyaoxiu2.sqlite.entity.ImChatType;
import com.zlb.leyaoxiu2.sqlite.entity.ImMessage;
import com.zlb.leyaoxiu2.sqlite.entity.ImUserInfo;
import com.zlb.leyaoxiu2.sqlite.entity.SystemMessage;

import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;

/**
 * Created by Administrator on 2016/8/17.
 */
public class ImMessageUtil {

    /**
     * 处理接收到私聊消息
     *
     * @param msg 接收到的JsonMessage
     */
    public static void saveMessage(Realm realm, PrivateChatNotify msg) {
        realm.beginTransaction();
        //插入消息信息
        ImMessage imMsg = new ImMessage();

        imMsg.setUserId(msg.getPeerId());//接受者=自己
        imMsg.setPeerId(msg.getUserId());//发送者
        if (msg.getUnique() == null) {
            msg.setUnique(UUIDUtil.getTempUUID());
            imMsg.setUnique(msg.getUnique());
        }
        imMsg.setUnique(msg.getUnique());
        imMsg.setContent(msg.getContent());
        imMsg.setMsgType(msg.getMsgType());
        imMsg.setUserLevel(msg.getUserLevel());

        imMsg.setExt1(msg.getExt1());
        imMsg.setMsgTime(msg.getMsgTime());
        imMsg.setUnRead(ImChatType.STATE_UN_READ);
        imMsg.setSendState(ImChatType.SEND_STATE_SUCCESS);
        imMsg.setMsgFrom(ImChatType.MSG_FORM_OTHER);
        // imMsg.setIsShowTime();

        realm.insertOrUpdate(imMsg);

        //插入发送者信息
        ImUserInfo imUserInfo = new ImUserInfo();
        imUserInfo.setUserId(msg.getUserId());
        imUserInfo.setIconUrl(msg.getIconUrl());
        imUserInfo.setNickName(msg.getNickName());
        imUserInfo.setUserLevel(msg.getUserLevel());
        realm.insertOrUpdate(imUserInfo);

        //插入系统消息
        SystemMessageUtil.insertOrUpdateSystemMessageByIm(realm, false, imMsg, msg.getNickName(), msg.getIconUrl());
        realm.commitTransaction();
    }


    /**
     * 处理发送消息
     *
     * @param realm
     * @param msg
     * @param peerName
     * @param peerIcon
     */
    public static void saveMessage(Realm realm, ImMessage msg, String peerName, String peerIcon) {
        if (msg != null) {
            realm.beginTransaction();
            realm.insertOrUpdate(msg);
            SystemMessageUtil.insertOrUpdateSystemMessageByIm(realm, false, msg, peerName, peerIcon);
            realm.commitTransaction();
        }
    }

    /**
     * 查询单个用户
     *
     * @param userId
     * @return
     */
    public static ImUserInfo findImUserInfo(Realm realm, String userId) {
        ImUserInfo result = realm.where(ImUserInfo.class)
                .equalTo("userId", userId).findFirst();
        return result;
    }

    /**
     * 插入或者更新Im好友信息
     *
     * @param userId
     * @param iconUrl
     * @param nickName
     */
    public static void insertOrUpdateImUserInfo(Realm realm, String userId, String iconUrl, String nickName) {
        realm.beginTransaction();
        ImUserInfo imUserInfo = new ImUserInfo();

        imUserInfo.setUserId(userId);
        imUserInfo.setIconUrl(iconUrl);
        imUserInfo.setNickName(nickName);

        realm.insertOrUpdate(imUserInfo);
        realm.commitTransaction();
    }

    /**
     * 修改消息发送状态
     *
     * @param unique
     * @param sendState
     */
    public static void updateMessageSendState(Realm realm, String unique, int sendState) {
        realm.beginTransaction();
        ImMessage result = realm.where(ImMessage.class).equalTo("unique", unique)
                .findFirst();
        if (result != null) {
            result.setSendState(sendState);
        }
        realm.commitTransaction();
    }

    /**
     * 单个会话详情-修改已读状态
     *
     * @param realm
     * @param userId
     * @param peerId
     * @param readState
     */
    public static void updateMessageReadState(Realm realm, String userId, String peerId, int readState) {
        realm.beginTransaction();
        RealmResults<ImMessage> results = realm.where(ImMessage.class)
                .beginGroup()
                .equalTo("peerId", peerId)
                .equalTo("userId", userId)
                .notEqualTo("unRead", readState)
                .endGroup()
                .findAll();
        if (results != null && results.size() > 0) {
            for (ImMessage msg : results) {
                msg.setUnRead(readState);
            }
        }
        updateSystemMessageReadState(realm, false, userId, peerId, 0);
        realm.commitTransaction();
    }

    /**
     * 更新单个会话未读消息
     *
     * @param realm
     * @param isBeginTs
     * @param userId
     * @param peerId
     * @param count
     */
    public static void updateSystemMessageReadState(Realm realm, Boolean isBeginTs, String userId, String peerId, int count) {
        if (isBeginTs) {
            realm.beginTransaction();
        }

        RealmResults<SystemMessage> results = realm.where(SystemMessage.class)
                .beginGroup()
                .equalTo("msgUnique", ImChatType.getSystemMsgUnique(userId, peerId))
                .endGroup()
                .findAll();
        if (results != null && results.size() > 0) {
            for (SystemMessage msg : results) {
                msg.setUnReadCount(count);
            }
        }
        if (isBeginTs) {
            realm.commitTransaction();
        }
    }

    /**
     * 所有消息列表-修改已读状态
     *
     * @param realm
     * @param readState
     */
    public static void updateTotalMessageReadState(Realm realm, String userId, int readState) {
        realm.beginTransaction();
        RealmResults<ImMessage> results = realm.where(ImMessage.class)
                .beginGroup()
                .equalTo("userId", userId)
                .notEqualTo("unRead", readState)
                .endGroup()
                .findAll();
        if (results != null && results.size() > 0) {
            for (ImMessage msg : results) {
                msg.setUnRead(readState);
            }
        }
        updateTotalSystemMessageReadState(realm, false, userId, 0);
        realm.commitTransaction();
    }

    /**
     * 更新单个会话未读消息
     *
     * @param realm
     * @param isBeginTs
     * @param count
     */
    public static void updateTotalSystemMessageReadState(Realm realm, Boolean isBeginTs, String userId, int count) {
        if (isBeginTs) {
            realm.beginTransaction();
        }

        RealmResults<SystemMessage> results = realm.where(SystemMessage.class).equalTo("userId", userId).findAll();
        if (results != null && results.size() > 0) {
            for (SystemMessage msg : results) {
                msg.setUnReadCount(count);
            }
        }
        if (isBeginTs) {
            realm.commitTransaction();
        }
    }

    public static RealmResults<ImMessage> getHistoryChat(Realm realm, String userId, String peerId) {
        return realm.where(ImMessage.class).equalTo("userId", userId).equalTo("peerId", peerId).findAll().sort("msgTime", Sort.DESCENDING);
    }

    /**
     * 单个会话详情的未读消息
     *
     * @param realm
     * @param userId
     * @param peerId
     * @return
     */
    public static int getUnReadCount(Realm realm, String userId, String peerId) {
        RealmResults<ImMessage> a = realm.where(ImMessage.class).equalTo("userId", userId)
                .equalTo("peerId", peerId).equalTo("unRead", ImChatType.STATE_UN_READ).findAll();
        return a.size();
    }

    /**
     * 所有的未读消息
     *
     * @param realm
     * @return
     */
    public static int getTotalUnReadCount(Realm realm, String userId) {
        boolean realmNull = false;
        if (realm == null) {
            realmNull = true;
            realm = Realm.getDefaultInstance();
        }

        RealmResults<ImMessage> a = realm.where(ImMessage.class).equalTo("userId", userId).
                equalTo("unRead", ImChatType.STATE_UN_READ).findAll();
        int size = a.size();

        if (realmNull) {
            realm.close();
        }
        return size;
    }
}